package com.rybbaby.tss.core.utils;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

/**
 * @description 此类以单利形式存储spring Application对象，方便程序在任何地方那个获取spring容器中的器资源
 * 
 * @author 谢进伟
 * 
 * @createDate 2016-1-26 上午12:43:51
 */
public class SpringApplicationContextUtil implements ApplicationContextAware {
	
	/**
	 * 服务器上下文对象
	 */
	private static ApplicationContext context = null;
	
	public void setApplicationContext(ApplicationContext context) throws BeansException {
		setContext(context);
	}
	
	/**
	 * @param context
	 *           spring容器上下文对象
	 *            此方法使用同步，防止多个类加载器重复初始化context对象
	 */
	private synchronized void setContext(ApplicationContext context) {
		if(SpringApplicationContextUtil.context == null) {
			SpringApplicationContextUtil.context = context;
		}
	}
	
	public static ApplicationContext getContext() {
		return context;
	}
	
	public static <T> T getBean(Class<T> cls) {
		return context.getBean(cls);
	}
}
